
package com.hmsg.health.controller.admin;


import com.hmsg.health.bean.vo.*;
import com.hmsg.health.dao.UserDao;
import com.hmsg.health.service.MenWangSMSService;
import com.hmsg.health.service.UserService;
import com.hmsg.health.service.admin.AdminUserService;
import com.hmsg.health.service.aes.SecurityData;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSBuilder;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyuncs.http.HttpResponse;
import com.hmsg.health.bean.domain.AdminUserDo;
import com.hmsg.health.bean.domain.UserAccountDo;
import com.hmsg.health.bean.domain.UserDo;
import com.hmsg.health.bean.enums.StatusCode;
import com.hmsg.health.config.Constants;
import com.hmsg.health.config.PropertyConfig;
import com.hmsg.health.param.AccessToken;
import com.hmsg.health.param.ResponseResult;
import com.hmsg.health.security.IgnoreSecurity;
import com.hmsg.health.security.OpenApi;
import com.hmsg.health.security.TokenManager;
import com.hmsg.health.utils.ApiException;
import com.hmsg.health.utils.ErrorCode;
import com.hmsg.health.utils.GetScene;
import com.hmsg.health.utils.HttpResult;
import com.hmsg.health.utils.HttpUtil;
import com.hmsg.health.utils.IdWorker;
import com.hmsg.health.utils.RandomUtil;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletResponse;

/**
 * @Author Tareva on 2018/11/11.
 * @Description TODO
 */
@Api(value = "运营系统登录相关", tags = { "运营系统登录相关" })
@Slf4j
@Controller
@RequestMapping("/admin")
public class AdminLoginController {

    @Autowired
	StringRedisTemplate stringTemplate;
    @Autowired
  	private MenWangSMSService smsService;
	@Autowired
	private TokenManager tokenManager;
    static final String XCODE_KEY = "XCODE_KEY_";
    @Autowired
  	PropertyConfig propertyConfig;
    @Autowired
    private UserService userService;

    static final IdWorker idWorker = new IdWorker(1);
    @Autowired
  	private AdminUserService adminUserService;

    
    @PostMapping("/login")
    @ResponseBody
    @IgnoreSecurity
	@OpenApi
	public  ResponseResult<Object> login(@RequestBody @Validated AdminUserLoginVo vo) {
    	
    	try {
    		if(vo.getPassword()==null||vo.getPassword().equals("")){
    			return new ResponseResult<Object>(StatusCode.PASSWORD_NOT_EXISE, null);
    		}
        	Map<String, Object> result = new HashMap<String, Object>();
        	
        	AdminUserDo info = new AdminUserDo();
        	info.setUserName(vo.getUserName());
    		List<AdminUserDo> users = adminUserService.select(info);
    		if(users!=null&&users.size()>0){
    			AdminUserDo user = users.get(0);
    			if(!user.getPassword().equals(vo.getPassword())){
    				return new ResponseResult<Object>(StatusCode.PASSWORD_ERROR, null);
    			}
    			AccessToken accessToken = tokenManager.createToken(Constants.TOKEN_SHUAWUJING,user.getId()+"");
    			user.setAccessToken(accessToken.getAccessToken());
    			result.put("user", user);
    			
    			return new ResponseResult<Object>(StatusCode.SYSTEM_SUCCESS, result);
    			
    		}else{
    			return new ResponseResult<Object>(StatusCode.USER_NOT_EXIST, null);
    		}
    	
		} catch (Exception e) {
			// TODO: handle exception
			return new ResponseResult<Object>(StatusCode.SYSTEM_ERROR, null);
		}
    	
	}
    
	// 发送验证码：1注册,2改密
	@PostMapping("/sendXcode")
	@ResponseBody
	@IgnoreSecurity
	@SecurityData
	public ResponseResult<Object> sendXcode(@RequestBody @Validated CodeReqVo codeReqVo) {
		 Map<String, Object> model = new HashMap<>();
		try {
			validateXcodeSendtime(codeReqVo.getMobile(), codeReqVo.getType()); 
			String xcode = RandomUtil.genRandomNum(6); 
			if("test".equals(propertyConfig.getProfile())){
				xcode="123456";
			}
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("xcode", xcode);
			map.put("createtime", String.valueOf(new Date().getTime()));
			stringTemplate.opsForHash().putAll(XCODE_KEY + codeReqVo.getType() + "_" + codeReqVo.getMobile(), map);
			stringTemplate.expire(XCODE_KEY + "_" + codeReqVo.getType() + codeReqVo.getMobile(), 1, TimeUnit.HOURS);
			String result = smsService.sendMessage(codeReqVo.getMobile(), xcode);
			/*if (result.length() > 10 && result.length() < 25) { // 返回的流水大于10位小于25位为提交成功
				smsMsg.setStatus(1);
			} else {
				smsMsg.setStatus(0);
			}
			smsMsg.setResult(result);
			smsMsg.setCreateTime(new Date());
			smsLogRepository.save(smsMsg);*/
			model.put("returnCode", "1");
			model.put("message", "");
			return new ResponseResult<Object>(StatusCode.SYSTEM_SUCCESS, model);
		} catch (Exception e) {
			// TODO: handle exception
			model.put("returnCode", "1");
			model.put("message", "");
			return new ResponseResult<Object>(StatusCode.SYSTEM_SUCCESS, model);
			
		}
		

		
	}
    
	private void validateXcodeSendtime(String mobile, int validateCodeType) {
		Object createtime = stringTemplate.opsForHash().get(XCODE_KEY + validateCodeType + "_" + mobile, "createtime");
		if (createtime != null) {
			long mills = Long.parseLong(createtime.toString());
			if (new Date().getTime() - mills < 60000) {
				throw new ApiException(ErrorCode.SEND_XCODE_TIME_ERROR);
			}
		}
	}
	
}

